﻿using System;
using System.Net;
using System.Text;
using System.Windows;
using eLearning.Model;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Newtonsoft.Json;
using eLearning.Util;

namespace eLearning.DosenView
{
    public partial class MemberDetailPage : PhoneApplicationPage
    {
        private Mahasiswa mahasiswa;
        private Perkuliahan kuliah;

        public MemberDetailPage()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(RssItemPage_Loaded);
        }

        private void RssItemPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (PhoneApplicationService.Current.State.ContainsKey(Config.KULIAH))
            {
                kuliah = (Perkuliahan)PhoneApplicationService.Current.State[Config.KULIAH];
                mahasiswa = kuliah.Mhs;
            }
            else if (PhoneApplicationService.Current.State.ContainsKey(Config.MHS))
            {
                mahasiswa = (Mahasiswa)PhoneApplicationService.Current.State[Config.MHS];
            }

            if (mahasiswa != null)
            {
                textMember.Text = mahasiswa.ToString();
                LoadPerkuliahanMember();
            }
        }

        private void LoadPerkuliahanMember()
        {

            string url = string.Format("{0}&{1}", Config.Instance.PERKULIAHAN_SERVICE_URL() + Config.VIEW_NILAI_MEMBER_KEY, Guid.NewGuid().ToString());
            string json = JsonConvert.SerializeObject(kuliah);

            Uri uri = new Uri(url, UriKind.Absolute);
            WebClient webClient = new WebClient();

            webClient.Encoding = Encoding.UTF8;
            webClient.Headers[HttpRequestHeader.ContentType] = "application/json";
            webClient.Headers[HttpRequestHeader.ContentLength] = json.Length.ToString();

            webClient.UploadStringCompleted += new UploadStringCompletedEventHandler(detailNilaiMember_UploadStringCompleted);
            try
            {
                webClient.UploadStringAsync(uri, "POST", json);
            }
            catch (Exception) { }

        }

        private void detailNilaiMember_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            if (e.Error != null)
                return;

            try
            {
                PerkuliahanList list = JsonConvert.DeserializeObject<PerkuliahanList>(e.Result);
                if (list.Count > 0)
                {
                    kuliah.Id = list[0].Id;
                    textUTS.Text = list[0].UTS.ToString();
                    textUAS.Text = list[0].UAS.ToString();
                    textTugas.Text = list[0].Tugas.ToString();
                    textQuiz.Text = list[0].Quiz.ToString();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void SavePerkuliahanMember(Perkuliahan kul)
        {
            string url = string.Format("{0}&{1}", Config.Instance.PERKULIAHAN_SERVICE_URL() + Config.SAVE_NILAI_MEMBER_KEY, Guid.NewGuid().ToString());
            string json = JsonConvert.SerializeObject(kul);

            Uri uri = new Uri(url, UriKind.Absolute);
            WebClient webClient = new WebClient();

            webClient.Encoding = Encoding.UTF8;
            webClient.Headers[HttpRequestHeader.ContentType] = "application/json";
            webClient.Headers[HttpRequestHeader.ContentLength] = json.Length.ToString();

            webClient.UploadStringCompleted += new UploadStringCompletedEventHandler(saveNilaiMember_UploadStringCompleted);
            try
            {
                webClient.UploadStringAsync(uri, "POST", json);
            }
            catch (Exception) { }

        }

        private void saveNilaiMember_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            if (e.Cancelled && e.Error != null)
            {
                return;
            }
            if (e.Result.Contains("saved"))
                LoadPerkuliahanMember();
            MessageBox.Show("Message : " + e.Result);
        }

        private void buttonSave_Click(object sender, System.EventArgs e)
        {
            if (!validInput())
            {
                return;
            }

            if (MessageBox.Show("Save data changes?", "", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
            {
                kuliah.UTS = textUTS.Text;
                kuliah.UAS = textUAS.Text;
                kuliah.Tugas = textTugas.Text;
                kuliah.Quiz = textQuiz.Text;
                SavePerkuliahanMember(kuliah);
            }
        }

        private void buttonCancel_Click(object sender, System.EventArgs e)
        {
            NavigationService.GoBack();
        }

        private bool validInput()
        {
            string uts = textUTS.Text;
            string uas = textUAS.Text;
            string tugas = textTugas.Text;
            string quiz = textQuiz.Text;

            if(!Utility.isNilaiQuiz(uts))
            {
                MessageBox.Show("Input nilai hanya A, B, C, D, atau E");
                textUTS.Focus();
                return false;
            }
            if (!Utility.isNilaiQuiz(uas))
            {
                MessageBox.Show("Input nilai hanya A, B, C, D, atau E");
                textUAS.Focus();
                return false;
            }
            if (!Utility.isNilaiQuiz(tugas))
            {
                MessageBox.Show("Input nilai hanya A, B, C, D, atau E");
                textTugas.Focus();
                return false;
            }
            if (!Utility.isNilaiQuiz(quiz))
            {
                MessageBox.Show("Input nilai hanya A, B, C, D, atau E");
                textQuiz.Focus();
                return false;
            }
            return true;
        }
    }
}